package com.starblink.brand.widget

import android.graphics.Rect
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.starblink.android.basic.BuildConfig
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.ext.load
import com.starblink.basic.ext.screenWidth
import com.starblink.brand.databinding.PopFindSimilarBrandProductBinding
import com.starblink.library.widget.product.ProductCardScene
import com.starblink.library.widget.product.parity.PriceParityDialog
import com.starblink.rocketreserver.FetchProductListByStdIdQuery
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.StdProductIdQuery
import com.starblink.store.view.StoreProductCompareDialog
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import razerdp.basepopup.BasePopupWindow
import razerdp.blur.PopupBlurOption
import razerdp.util.log.PopupLog


class BrandProductsFindSimilarPop : BasePopupWindow {
    private val binding = PopFindSimilarBrandProductBinding.inflate(LayoutInflater.from(context))

    constructor(
        activity: FragmentActivity,
        product: ProductF,
        anchorView: View,
        spmPageValue: Int,
        addClick: (() -> Unit),
    ) : super(activity) {
        this.activity = activity
        this.product = product
        this.anchorView = anchorView
        this.spmPageValue = spmPageValue
        this.addClick = addClick
    }

    private val activity: FragmentActivity
    private var product: ProductF
    private var spmPageValue: Int
    private val addClick: () -> Unit
    private val anchorView: View

    private val halfScreenW = screenWidth.shr(1)

//    fun showPopup(anchorView: View, product: ProductF) {
//        val p = prepare(anchorView)
//        this.product = product
//        showPopupWindow()
//    }

    init {
        contentView = binding.root
        PopupLog.setOpenLog(BuildConfig.DEBUG)
    }

    /**
     * ！！！注意！！！在Init中回调，在构造函数之前调用，此时参数没有值
     */
    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        // 背景色
        setBlurBackgroundEnable(true)
        setBlurOption(
            PopupBlurOption()
                .setFullScreen(true)
                .setBlurInDuration(-1L)
                .setBlurOutDuration(-1L)
                .setBlurRadius(10F)
                .setBlurView(context?.window?.decorView)
                .setBlurPreScaleRatio(0.25F)
        )
        setBackgroundColor(context.color(com.starblink.basic.style.R.color.clr_ad0f172a))
    }

    override fun onBeforeShow(): Boolean {
        val superVal = super.onBeforeShow()
        // 大图
        val drawable = (anchorView as? ImageView?)?.drawable
        if (drawable != null) {
            binding.img.setImageDrawable(drawable)
        } else {
            binding.img.load(product.mainImg)
        }

        // 设置菜单视图靠左靠右(默认靠右)
        val array = intArrayOf(0, 0)
        anchorView.getLocationInWindow(array)
        val anchorRect = Rect(
            array[0],
            array[1],
            array[0] + anchorView.measuredWidth,
            array[1] + anchorView.measuredHeight
        )
        if (anchorRect.left < halfScreenW) {
            binding.layoutMenu.updateLayoutParams<LinearLayout.LayoutParams> {
                gravity = Gravity.LEFT
            }
        }

        // 找相似
        binding.layoutFindSimilar.click {
            dismiss()
            if (product.mainImg.isNullOrEmpty().not() && product.id.isNullOrEmpty().not()) {
                CommonRoute.toFindSimilarGoods(product.mainImg!!, product.id!!, product.type)
            }
        }

        // 比价,有时显示
        binding.layoutComparePrices.visibleOrGone(
            (product.brotherOffers?.size ?: 0) >= 2 && product.standardSpuIds.isNullOrEmpty().not()
        ) {
            click {
                dismiss()
                showParityDialog()
            }
        }

        // 收藏
        binding.vAddText.text = if (product.collected == true) "Added" else "Add"
        binding.vAddIcon.setImageResource(if (product.collected == true) com.starblink.library.widget.R.drawable.ic_wishlist_product_collected else com.starblink.library.widget.R.drawable.ic_wishlist_product_collect)
        binding.layoutAdd.setOnClickListener {
            dismiss()
            addClick.invoke()
        }

        binding.root.setOnClickListener {
            dismiss()
        }

        return superVal
    }

    private val theScope get() = (context as? AppCompatActivity?)?.lifecycleScope ?: MainScope()
    private fun showParityDialog() {
        (context as? AppCompatActivity?)?.let { activity ->
            theScope.launch {
                SkGqlClient.skQuery(
                    FetchProductListByStdIdQuery(
                        stdProdcutIdQuery = StdProductIdQuery(
                            stdProductId = product.standardSpuIds!!,
                            includeInValidProd = false.optional(),
                        ).optional()
                    ),
                    showDefaultLoading = true,
                )?.data?.fetchProductListByStdId?.run {
                    this.mapNotNull { it?.productOffer }
                }?.let {
                    PriceParityDialog.show(
                        activity.supportFragmentManager,
                        product = product,
                        it,
                        spmPageValue = spmPageValue
                    )
                }
            }
        }
    }
}